package com.paic.mhis.hcpms.assessment.biz.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.paic.mhis.common.base.intergration.dao.CommonDAO;
import com.paic.mhis.common.util.BusinessServiceUtil;
import com.paic.mhis.hcpms.assessment.biz.service.AssessmentIndicatorService;
import com.paic.mhis.hcpms.assessment.biz.service.ExportWordService;
import com.paic.mhis.hcpms.assessment.biz.service.PerformanceDataService;
import com.paic.mhis.hcpms.assessment.common.AssessmentConstants;
import com.paic.mhis.hcpms.assessment.common.AssessmentSqlMapIdConstants;
import com.paic.mhis.hcpms.assessment.dto.IndicatorConfigInfoDTO;
import com.paic.mhis.hcpms.assessment.dto.PerformanceDataDTO;
import com.paic.mhis.hcpms.assessment.dto.PerformanceThreeDataDTO;
import com.paic.mhis.hcpms.assessment.intergration.dao.PerformanceDataDAO;
import com.paic.mhis.hcpms.assessment.util.AssessmentUtils;
import com.paic.pafa.app.biz.service.BusinessServiceException;

/**
 * 
 * Description:数据录入模块ServiceImpl
 * 
 * @author: EX-HUANGJUN003
 * @version:
 */
@Service("performanceDataService")
public class PerformanceDataServiceImpl implements PerformanceDataService {

	private static final Log LOG = LogFactory
			.getLog(PerformanceDataServiceImpl.class);

	@Resource(name = "commonDao")
	private CommonDAO commonDao;

	@Resource(name = "performanceDataDAO")
	private PerformanceDataDAO performanceDataDAO;

	@Autowired
	private ExportWordService exportWordService;

	@Autowired
	private AssessmentIndicatorService assessmentIndicatorService;

	/**
	 * 
	 * Description: 查询指标详情
	 * 
	 * @param paramMap
	 * @return
	 * 
	 *         Modification History: Date Version Author Description
	 *         ------------
	 *         ------------------------------------------------------ 2015-3-5
	 *         mhis_hcpms EX-HUANGJUN003 创建
	 */
	@SuppressWarnings("unchecked")
	@Override
	@Transactional(rollbackFor = Exception.class)
	public List<PerformanceDataDTO> getPerformanceDataList(
			Map<String, Object> paramMap) throws BusinessServiceException {
		if (StringUtils.equals(AssessmentConstants.INDICATOR_LEVEL0,
				paramMap.get("indicatorLevel") + "")
				|| StringUtils.equals(AssessmentConstants.INDICATOR_LEVEL3,
						paramMap.get("indicatorLevel") + "")) {
			List<PerformanceDataDTO> levelList = null;
			List<PerformanceDataDTO> targetList = null;
			try {
				levelList = commonDao.query(
						"performanceDataService.getPerformanceDataList",
						paramMap);
				targetList = targetDto(levelList, paramMap);
			} catch (Exception e) {
				LOG.error(e.getMessage(), e);
				BusinessServiceUtil.processException(e);
			}
			return targetList;

		} else {
			List<PerformanceDataDTO> detailList = null;
			try {
				paramMap.put("indicatorLevel",
						AssessmentConstants.INDICATOR_LEVEL1);
				List<PerformanceDataDTO> levelList1 = commonDao.query(
						"performanceDataService.getPerformanceDataList",
						paramMap);
				List<PerformanceDataDTO> targetList1 = targetDto(levelList1,
						paramMap);

				paramMap.put("indicatorLevel",
						AssessmentConstants.INDICATOR_LEVEL2);
				List<PerformanceDataDTO> levelList2 = commonDao.query(
						"performanceDataService.getPerformanceDataList",
						paramMap);
				List<PerformanceDataDTO> targetList2 = targetDto(levelList2,
						paramMap);

				paramMap.put("indicatorLevel",
						AssessmentConstants.INDICATOR_LEVEL3);
				List<PerformanceDataDTO> levelList3 = commonDao.query(
						"performanceDataService.getPerformanceDataList",
						paramMap);
				List<PerformanceDataDTO> targetList3 = targetDto(levelList3,
						paramMap);

				detailList = new ArrayList<PerformanceDataDTO>();
				for (PerformanceDataDTO map : targetList1) {
					List<PerformanceDataDTO> detailList1 = new ArrayList<PerformanceDataDTO>();

					for (PerformanceDataDTO map1 : targetList2) {
						// 如果二级指标的pcode等于一级指标code
						if (StringUtils.equals(map1.getDegaultPcode() + "",
								map.getIndicatorCode() + "")) {
							detailList1.add(map1);
							map.setList(detailList1);
						}
						List<PerformanceDataDTO> detailList2 = new ArrayList<PerformanceDataDTO>();
						for (PerformanceDataDTO map2 : targetList3) {
							// 如果三级指标的pcode等于二级指标code
							if (StringUtils.equals(map2.getDegaultPcode() + "",
									map1.getIndicatorCode() + "")) {
								detailList2.add(map2);
							}
						}
						// 对象转换
						List<PerformanceDataDTO> result = changeDto(detailList2);
						map1.setList(result);
					}
					detailList.add(map);
				}
			} catch (Exception e) {
				LOG.error(e.getMessage(), e);
				BusinessServiceUtil.processException(e);
			}
			return detailList;
		}

	}

	/**
	 * 
	 * Description: 根据对应医院编码和时间维度删除指标分数记录
	 * 
	 * @param paramMap
	 * 
	 *            Modification History: Date Version Author Description
	 *            ----------
	 *            --------------------------------------------------------
	 *            2015-3-5 mhis_hcpms EX-HUANGJUN003 创建
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteThreeList(Map<String, Object> paramMap) {
		try {
			performanceDataDAO.delete("performanceDataService.deleteThreeList",
					paramMap);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
	}

	/**
	 * 
	 * Description:根据对应医院编码和时间维度插入指标分数记录
	 * 
	 * @param list
	 * 
	 *            Modification History: Date Version Author Description
	 *            ----------
	 *            --------------------------------------------------------
	 *            2015-3-5 mhis_hcpms EX-HUANGJUN003 创建
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public void insertThreeList(List<PerformanceThreeDataDTO> list,
			Map<String, Object> map) {
		try {

			deleteThreeList(map);
			deleteThreeDataList(map);

			insertThreeDataList(list);
			List<PerformanceThreeDataDTO> listDto = new ArrayList<PerformanceThreeDataDTO>();
			for (PerformanceThreeDataDTO dto : list) {
				if (StringUtils.equals(AssessmentConstants.SOURCE_TYPE2,
						dto.getSourceType())) {
					listDto.add(dto);
				}

			}

			commonDao.insertBatch("performanceDataService.insertThreeList",
					listDto);

			Map<String, Object> paramsMap = new HashMap<String, Object>();
			paramsMap.put("providerCode", map.get("providerCode"));
			paramsMap.put("period", map.get("period"));
			paramsMap.put("kpiTime", map.get("kpiTime"));
			paramsMap.put("regionCode", map.get("regionCode"));
			paramsMap.put("regioncode", map.get("regionCode"));
			paramsMap.put("level", AssessmentConstants.INDICATOR_LEVEL2);
			// 获取指标体系编号需要的参数
			Map<String, Object> parameterMap = exportWordService
					.getHospitalInfo(map.get("providerCode") + "");
			Map<String, Object> dateMapParameter = new HashMap<String, Object>();
			dateMapParameter.put("grade", parameterMap.get("HOSLEVEL"));
			dateMapParameter.put("regioncode", parameterMap.get("REGIONCODE"));

			paramsMap.put("structureNo",
					exportWordService.getStructureNo(dateMapParameter));

			commonDao.insert(
					AssessmentSqlMapIdConstants.ASSESSMENT_INSERT_PARENT_SCORE,
					paramsMap);

			paramsMap.put("level", AssessmentConstants.INDICATOR_LEVEL1);
			commonDao.insert(
					AssessmentSqlMapIdConstants.ASSESSMENT_INSERT_PARENT_SCORE,
					paramsMap);

			// 刷父指标得分
			paramsMap.put("level", AssessmentConstants.INDICATOR_LEVEL0);
			commonDao.insert(
					AssessmentSqlMapIdConstants.ASSESSMENT_INSERT_PARENT_SCORE,
					paramsMap);

			System.out.println(paramsMap);
			// 刷新指标得分百分比
			commonDao
					.update(AssessmentSqlMapIdConstants.ASSESSMENT_UPDATE_PERCENT_SCORE,
							paramsMap);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}

	}

	/**
	 * 
	 * Description:根据对应医院编码和时间维度删除指标数据表中指标分数记录
	 * 
	 * @param paramMap
	 * 
	 *            Modification History: Date Version Author Description
	 *            ----------
	 *            --------------------------------------------------------
	 *            2015-3-5 mhis_hcpms EX-HUANGJUN003 创建
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteThreeDataList(Map<String, Object> paramMap) {
		try {
			performanceDataDAO.delete(
					"performanceDataService.deleteThreeDataList", paramMap);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
	}

	/**
	 * 
	 * Description:根据对应医院编码和时间维度对指标数据表插入指标分数记录
	 * 
	 * @param list
	 * 
	 *            Modification History: Date Version Author Description
	 *            ----------
	 *            --------------------------------------------------------
	 *            2015-3-5 mhis_hcpms EX-HUANGJUN003 创建
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void insertThreeDataList(List<PerformanceThreeDataDTO> list) {
		List<PerformanceThreeDataDTO> listDto = new ArrayList<PerformanceThreeDataDTO>();
		try {
			for (PerformanceThreeDataDTO dto : list) {
				if (StringUtils.equals(AssessmentConstants.SOURCE_TYPE2,
						dto.getSourceType())) {

					listDto.add(dto);
				}

			}
			commonDao.insertBatch("performanceDataService.insertThreeDataList",
					listDto);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}

	}

	/**
	 * 
	 * Description: 对象转换
	 * 
	 * @param list
	 * @return
	 * 
	 *         Modification History: Date Version Author Description
	 *         ------------
	 *         ------------------------------------------------------ 2015-3-6
	 *         mhis_hcpms EX-HUANGJUN003 创建
	 */
	private List<PerformanceDataDTO> changeDto(List<PerformanceDataDTO> list) {
		int count = 1;
		List<PerformanceDataDTO> result = new ArrayList<PerformanceDataDTO>();
		PerformanceDataDTO searchVo = null;
		for (PerformanceDataDTO map3 : list) {

			if (count % 2 == 1) {
				searchVo = new PerformanceDataDTO();
				searchVo.setName1(map3.getIndicatorName());
				searchVo.setScore1(map3.getStructureScore());
				searchVo.setSourceType1(map3.getSourceType());
				searchVo.setIndicatorCode1(map3.getIndicatorCode());
				searchVo.setPercentScore1(map3.getPercentScore());
				searchVo.setVisitType1(map3.getVisitType());
				searchVo.setFullMark1(map3.getFullMark());
				searchVo.setStandardType1(map3.getStandardType());
				searchVo.setIndicatorValue1(map3.getIndicatorValue());
				searchVo.setUpperLimit1(map3.getUpperLimit());
				searchVo.setLowerLimit1(map3.getLowerLimit());
				searchVo.setUnit1(map3.getUnit());
				searchVo.setEvaluationMethod1(map3.getEvaluationMethod());
				searchVo.setValue1(map3.getValue());
				searchVo.setKpiTime(map3.getKpiTime());
				searchVo.setProviderCode(map3.getProviderCode());
				searchVo.setRegionCode(map3.getRegionCode());
			} else if (count % 2 == 0) {
				searchVo.setName2(map3.getIndicatorName());
				searchVo.setScore2(map3.getStructureScore());
				searchVo.setSourceType2(map3.getSourceType());
				searchVo.setIndicatorCode2(map3.getIndicatorCode());
				searchVo.setPercentScore2(map3.getPercentScore());
				searchVo.setVisitType2(map3.getVisitType());
				searchVo.setFullMark2(map3.getFullMark());
				searchVo.setStandardType2(map3.getStandardType());
				searchVo.setIndicatorValue2(map3.getIndicatorValue());
				searchVo.setUpperLimit2(map3.getUpperLimit());
				searchVo.setLowerLimit2(map3.getLowerLimit());
				searchVo.setUnit2(map3.getUnit());
				searchVo.setEvaluationMethod2(map3.getEvaluationMethod());
				searchVo.setValue2(map3.getValue());
			}

			if (count % 2 == 0 || count == list.size()) {
				result.add(searchVo);
			}

			count++;
		}
		return result;
	}

	/**
	 * 
	 * Description: 对象转换
	 * 
	 * @param list
	 * @return
	 * 
	 *         Modification History: Date Version Author Description
	 *         ------------
	 *         ------------------------------------------------------ 2015-3-6
	 *         mhis_hcpms EX-HUANGJUN003 创建
	 */
	private List<PerformanceDataDTO> targetDto(List<PerformanceDataDTO> list,
			Map<String, Object> paramMap) {
		for (PerformanceDataDTO dto : list) {
			IndicatorConfigInfoDTO configDto = assessmentIndicatorService
					.getIndicatorConfig(dto.getIndicatorCode(),
							paramMap.get("regionCode") + "",
							paramMap.get("grade") + "");

			dto.setEvaluationMethod(configDto.getEvaluationMethod());
			dto.setValue(configDto.getValue());
			if (StringUtils.equals(AssessmentConstants.STANDARD_TYPE2,
					configDto.getEvaluationMethod())
					&& dto.getUpperLimit().compareTo(new BigDecimal(0)) == 0) {
				dto.setLowerLimit(configDto.getValue());
				dto.setUpperLimit(new BigDecimal(100));
			}
			// 如果是接口数据，设置kpivalue即data表中得分 *100
			if (StringUtils.equals(dto.getSourceType(),
					AssessmentConstants.SOURCE_TYPE3)) {
				dto.setIndicatorValue(AssessmentUtils.decimalToDecimal(dto
						.getIndicatorValue().multiply(new BigDecimal(100))));
			} else {
				dto.setIndicatorValue(AssessmentUtils.decimalToDecimal(dto
						.getIndicatorValue()));
			}
		}
		return list;
	}

}
